package controllers

import (
	"fmt"
	"time"

	"ErgoGo/internal/model/article"
	"ErgoGo/internal/model/conf"

	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
)

// Activity 表示一条活动记录
type Activity struct {
	Icon    string
	Color   string
	Content string
	Time    string
}

// Dashboard 处理仪表盘页面
func Dashboard(c *gin.Context) {
	// 获取用户信息
	userName := c.GetString("userName")
	if userName == "" {
		userName = "管理员"
	}

	// 获取当前日期
	currentDate := time.Now().Format("2006年01月02日")

	// 获取统计数据
	todayArticles := getTodayArticles()
	totalArticles := getTotalArticles()
	systemStatus := getSystemStatus()
	apiCalls := getApiCalls()

	// 获取最近活动
	recentActivities := getRecentActivities()

	c.HTML(200, "dashboard", gin.H{
		"title":            "仪表盘",
		"userName":         userName,
		"currentDate":      currentDate,
		"todayArticles":    todayArticles,
		"totalArticles":    totalArticles,
		"systemStatus":     systemStatus,
		"apiCalls":         apiCalls,
		"recentActivities": recentActivities,
		"showHeader":       true,
		"active":           "dashboard",
	})
}

// getTodayArticles 获取今日生成的文章数量
func getTodayArticles() int {
	count := article.GetTodayArticles()
	return count
}

// getTotalArticles 获取总文章数量
func getTotalArticles() int {
	count := article.GetTotalArticles()
	return count
}

// getSystemStatus 获取系统状态
func getSystemStatus() string {
	return "运行正常"
}

// getApiCalls 获取API调用次数
func getApiCalls() int {
	count := conf.GetConfig(conf.ApiCount)
	return cast.ToInt(count)
}

// getRecentActivities 获取最近活动记录
func getRecentActivities() (activity []Activity) {
	lastCreatedArticle := article.GetLastCreatedArticle()
	lastPublishArticle := article.GetLastPublishArticle()

	if lastCreatedArticle.ID != 0 {
		activity = append(activity, Activity{
			Icon:    "fa-file-alt",
			Color:   "blue",
			Content: "生成新文章：" + lastCreatedArticle.Title,
			Time:    formatTime(lastCreatedArticle.CreatedAt),
		})
	}

	if lastPublishArticle.ID != 0 {
		activity = append(activity, Activity{
			Icon:    "fa-check-circle",
			Color:   "green",
			Content: "文章发布成功：" + lastPublishArticle.Title,
			Time:    formatTime(lastPublishArticle.UpdatedAt),
		})
	}
	return
}

// formatTime 格式化时间显示
func formatTime(t time.Time) string {
	now := time.Now()
	diff := now.Sub(t)

	switch {
	case diff < time.Minute:
		return "刚刚"
	case diff < time.Hour:
		minutes := int(diff.Minutes())
		return fmt.Sprintf("%d分钟前", minutes)
	case diff < 24*time.Hour:
		hours := int(diff.Hours())
		return fmt.Sprintf("%d小时前", hours)
	case diff < 30*24*time.Hour:
		days := int(diff.Hours() / 24)
		return fmt.Sprintf("%d天前", days)
	default:
		return t.Format("2006-01-02 15:04")
	}
}
